package com.lmonkey.filter;

import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@MultipartConfig
@WebFilter("/shangc/getphoto")
public class GetPhoto implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest reqq = (HttpServletRequest) req;
        HttpServletResponse respp = (HttpServletResponse) resp;
        //设置字符集
        reqq.setCharacterEncoding("UTF-8");
        respp.setContentType("text/html;charset=utf-8");
        PrintWriter out = respp.getWriter();
        //获取参数
        Part part = reqq.getPart("photo");
        String file = part.getSubmittedFileName();
        if (file == "") {
            out.println("<script>alert('请上传头像');location.href='mygrxxselect';</script>");
            out.close();
            return;
        } else {
            Pattern pt = Pattern.compile(".+(.jpg|.png|.JPG|.PNG)$");
            Matcher mc = pt.matcher(file);
            if (!mc.matches()){
                out.println("<script>alert('头像文件格式不正确');location.href='mygrxxselect';</script>");
                out.close();
                return;
            }
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
